package cn.algorithms_4ed.algo.union_find;

import cn.stdlib.In;
import cn.stdlib.StdOut;

/**
 * quick find
 * <p/>
 * User: erhu
 * Date: 13-6-12
 * Time: 下午8:55
 */
public class UFQuickFind {

    int[] id;
    // 连通分量数
    int count;

    public UFQuickFind(int _count) {
        count = _count;
        id = new int[_count];
        for (int i = 0; i < _count; i++) {
            id[i] = i;
        }
    }

    public int count() {
        return count;
    }

    protected int find(int p) {
        return id[p];
    }

    public boolean collected(int p, int q) {
        return find(p) == find(q);
    }

    protected void union(int p, int q) {
        int p_id = find(p);
        int q_id = find(q);
        if (p_id == q_id)
            return;
        for (int i = 0; i < id.length; i++) {
            if (id[i] == p_id) {
                id[i] = q_id;
            }
        }
        count--;
    }


    public static void main(String[] args) {
        long begin = System.currentTimeMillis();

        String file_medium = "/Users/erhu/Dropbox/workspace/java-study/algs4-data/mediumUF.txt";
        In in = new In(file_medium);
        int N = in.readInt();

        UFQuickFind uf = new UFQuickFind(N);
        while (!in.isEmpty()) {
            int p = in.readInt();
            int q = in.readInt();
            if (uf.collected(p, q)) {
                continue;
            }
            uf.union(p, q);
            StdOut.println(p + " " + q);
        }
        StdOut.print(uf.count() + " components.");

        StdOut.println("time: " + (System.currentTimeMillis() - begin));
    }
}
